package com.jpo.common.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class MyMultipartFile implements MultipartFile {

    private byte[] imgContent;
    private String header;

    public void Base64DecodedMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    public MyMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        return String.join(String.valueOf(System.currentTimeMillis()), String.valueOf(Math.random()), ".", header.split("/")[1]);
    }

    @Override
    public String getOriginalFilename() {
        return String.join(String.valueOf(System.currentTimeMillis()), String.valueOf((int) (Math.random() * 10000)), ".", header.split("/")[1]);
    }

    @Override
    public String getContentType() {
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(dest)) {
            outputStream.write(imgContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
